//
//  DiscoveryViewController.m
//  TinyFortune
//
//  Created by lc on 16/6/10.
//  Copyright © 2016年 lc. All rights reserved.
//
#import "DiscoveryViewController.h"
#import <MapKit/MapKit.h>
#import "LCSegmentdeControl.h"
#import "FirstCollectionCell.h"
#import "SecondCollectionCell.h"
#import "CLLocation+Sino.h"
#import "discoveryModel.h"
#import "discoveryModel.h"
#import "secondDisViewController.h"


NSString *const firstCellIdentifier = @"firstCell";
NSString *const secondCellIdentifier = @"secondCell";
@interface DiscoveryViewController ()<CLLocationManagerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    LCSegmentdeControl *_segment;//分栏控制器
    CLLocationManager *_locationManager;//定位服务器管理对象
    //section的头视图
    UIView *_headerView;
    //滚动视图
    UIScrollView *_collectionHeader;
    //sectionHeader的标题
    UILabel *_sectionLabel;
    NSString *_lastCity;//当前城市
    NSString *_lastAddress;//省地质
    CLLocation *_currentLocation;//当前位置
}
//collectionView三件套
@property (nonatomic,strong)NSMutableArray *collectionArray;
@property (nonatomic,strong)AFHTTPSessionManager *httpManager;
@end

@implementation DiscoveryViewController
#pragma mark - 懒加载
- (AFHTTPSessionManager *)httpManager{
    if (!_httpManager) {
        _httpManager = [AFHTTPSessionManager manager];
        //设置JSON序列化,将JSON数据转换为字典或者数组
        _httpManager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //在序列化器中追加一个类型text/html(原本只支持text/json,application/json)
        _httpManager.responseSerializer.acceptableContentTypes = [_httpManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
      
    }
    return _httpManager;
}
- (NSMutableArray *)collectionArray{
    if(!_collectionArray){
        _collectionArray = [NSMutableArray new];
    }
    return _collectionArray ;
}
#pragma mark - 界面搭建
- (void)createFirst{
    //实例化section的头部视图
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LC_WIDTH, 30)];
    _headerView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    //装饰View
    UIView *tView = [UIView new];
    [_headerView addSubview:tView];
    tView.translatesAutoresizingMaskIntoConstraints = NO;
    [tView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView.mas_left).offset(5);
        make.top.equalTo(_headerView.mas_top).offset(5);
        make.bottom.equalTo(_headerView.mas_bottom).offset(-5);
        make.width.equalTo(@5);
        make.height.equalTo(@20);
    }];
    tView.layer.masksToBounds = YES ;
    tView.layer.cornerRadius = 5 ;
    tView.backgroundColor = [UIColor cyanColor];
    //标题
    _sectionLabel.backgroundColor = [UIColor clearColor];
    _sectionLabel = [UILabel new];
    [_headerView addSubview:_sectionLabel];
    _sectionLabel.translatesAutoresizingMaskIntoConstraints = NO ;
    [_sectionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headerView.mas_top).offset(5);
        make.bottom.equalTo(_headerView.mas_bottom).offset(-5);
        make.left.equalTo(_headerView.mas_left).offset(15);
        make.width.equalTo(@100);
        make.height.equalTo(@20);
    }];
    _sectionLabel.text=@"精品推荐";
    _sectionLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    _sectionLabel.adjustsFontSizeToFitWidth = YES;
    
    
    
}
- (void)createUI{
    //注册cell(告诉collectionView在自动创建cell的时候,需要创建什么样的cell)
    // [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    self.collectionView.delegate = self ;
    self.collectionView.dataSource = self ;
    [self.collectionView reloadData];
    //注册单元格
    [_collectionView registerNib:[UINib nibWithNibName:@"FirstCollectionCell" bundle:nil] forCellWithReuseIdentifier:firstCellIdentifier];
    [_collectionView registerNib:[UINib nibWithNibName:@"SecondCollectionCell" bundle:nil]forCellWithReuseIdentifier:secondCellIdentifier];
    //注册section头部视图
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionHeader"];
    __weak typeof(self)weakSelf = self;
    self.collectionView.mj_header =[MJRefreshHeader headerWithRefreshingBlock:^{
        weakSelf .collectionView.mj_footer.hidden = YES;
        [weakSelf requestWithlatitude:_latitude longtitude:_longtitude start:0 count:20];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage ++;
        //隐藏header
        weakSelf.collectionView.mj_header.hidden = YES;
        [weakSelf requestWithlatitude:_latitude longtitude:_longtitude start:weakSelf.currentPage count:20];
    }];
    
    [self.collectionView reloadData];
    self.requestUrl = LC_Spot;
    [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
    //实例化分栏控制器
    _segment =[[LCSegmentdeControl alloc]initWithItems:@[@"景点",@"住宿",@"餐厅",@"娱乐",@"购物"]];
    _segment.frame = CGRectMake(0, 0, LC_WIDTH, 40);
    _segment.normalColor = [UIColor whiteColor];
    _segment.selectedColor = [UIColor colorWithRed:223/255.0f green:223/255.0f blue:223/255.0f alpha:1];
    _segment.selectedSegmentIndex = 0 ;
    [_segment addTarget:self action:@selector(clickSegment:)];
    self.navigationItem.titleView = _segment;
    
    //实例化当前位置
    
    _locationView.backgroundColor = [UIColor colorWithRed:241/251.0f green:75/255.0f blue:70/255.0f alpha:0.8];
    //_locationView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showLocation:)];
    [_locationView addGestureRecognizer:tap];
    
}
#pragma mark - 展示地图
- (void)showLocation:(UITapGestureRecognizer *)sender{
    
}
#pragma mark - 分栏控制器点击事件
- (void)clickSegment:(LCSegmentdeControl *)seg{
    switch (seg.selectedSegmentIndex) {
        
        case 0:{
            self.requestUrl = LC_Spot;
            [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
            break;
        }
        case 1:{
            self.requestUrl = LC_Live;
            [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
            break;
        }
        case 2:{
            self.requestUrl = LC_Restaurant;
            [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
            break;
        }
        case 3:{
            self.requestUrl = LC_Entertainment;
            [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
            break;
        }
        case 4:{
            self.requestUrl = LC_Shopping;
            [self requestWithlatitude:self.latitude longtitude:self.longtitude start:0 count:20];
            break;
        }
            
    }
}
#pragma mark - flowLayout协议
//设置单元格size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //间距
    CGFloat margin = 10.0f ;
    if (indexPath.section == 0) {
        //设置单元格的size
        return CGSizeMake(LC_WIDTH/2.0f - margin/2.0 , 180);
    }else{
        return CGSizeMake(LC_WIDTH , LC_WIDTH *3.8/5.0f);
        
    }
}
//MARK:设置最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 5 ;
    }
}
//MARK:设置最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 10 ;
    }else{
        return  10 ;
    }
}

#pragma mark - uiCollectionView协议
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    secondDisViewController *secVC = [sb instantiateViewControllerWithIdentifier:@"secondDisViewController"];
     //传值到下一界面
    if (indexPath.section == 0) {
        secVC.model = self.collectionArray[indexPath.row];
    }else{
        secVC.model = self.collectionArray[indexPath.row + 4];
    }
   
    
    [self.navigationController pushViewController:secVC animated:NO];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
        //return self.collectionArray.count ;
    }else{
        return  self.collectionArray.count;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return  2 ;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FirstCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstCellIdentifier forIndexPath:indexPath];
        if (self.collectionArray.count >3) {
            discoveryModel *model = self.collectionArray[indexPath.row];
            cell.model = model ;
        }
        cell.backgroundColor = [UIColor whiteColor];
        cell.layer.masksToBounds = YES ;
        cell.layer.cornerRadius = 5;
        return cell;
    }else{
        
        SecondCollectionCell *secondCell = [collectionView dequeueReusableCellWithReuseIdentifier:secondCellIdentifier forIndexPath:indexPath];
        if (indexPath.row + 4 < self.collectionArray.count) {
        discoveryModel *model = self.collectionArray[indexPath.row + 4];
        secondCell.backgroundColor = [UIColor whiteColor];
        secondCell.model = model;
        }
        return secondCell;
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionHeader" forIndexPath:indexPath];
            [self createFirst];
            [reusableView addSubview:_headerView];
            return reusableView ;
        }else{
            UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionHeader" forIndexPath:indexPath];
            [self createFirst];
            _sectionLabel.text = @"精彩周边";
            [reusableView addSubview:_headerView];
            return reusableView ;
        }
    }
    return  nil ;
}
#pragma mark - 生命周期
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //创建定位服务管理器对象
    _locationManager = [CLLocationManager new];
    //定位精确度,如果设置成best就特别费电
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //距离过滤器,设置越小越耗电
    _locationManager.distanceFilter = 10 ;
    //绑定时间回调
    _locationManager.delegate = self ;
    
    
    
    //======================地图==============================
    //先获得定位服务授权状态
    CLAuthorizationStatus staus = [CLLocationManager authorizationStatus];
    
    //如果尚未授权
    if (staus == kCLAuthorizationStatusNotDetermined) {
        
        //请求在应用程序使用期间授权定位服务
        //请求授权使用定位服务(始终)
        [_locationManager requestAlwaysAuthorization];
    }else if (staus == kCLAuthorizationStatusDenied){
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"主人还没开启定位设置,现在去设置一下咯~~" preferredStyle:UIAlertControllerStyleActionSheet];
        //打开设置的按钮
        UIAlertAction *openAction = [UIAlertAction actionWithTitle:@"打开设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //打开应用程序的设置
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication]openURL:url];
        }];
        //取消按钮
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        //将两个ACtion放到视图控制器上
        [alertController addAction:openAction];
        [alertController addAction:cancelAction];
        //以模态的方式显示警告视图控制器
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    
    [self createUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedAlways) {
        //开始启用定位服务
        [_locationManager startUpdatingLocation];
    }
}
//更新坐标
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //当前坐标
    _currentLocation = [locations firstObject];
    //当前坐标转火星坐标
   // CLLocation *currentLocationMars = [currentLocation locationMarsFromEarth];
    //经纬度获取
    CLLocationCoordinate2D lastCoordinate ;
    lastCoordinate = CLLocationCoordinate2DMake(_currentLocation.coordinate.latitude, _currentLocation.coordinate.longitude);
    //longtitude经度
    _longtitude = _currentLocation.coordinate.longitude;
    //latitude维度
    _latitude = _currentLocation.coordinate.latitude;
   
    //地理信息获取
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:_currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //通过经纬度查询到地里信息
        if (placemarks.count > 0) { //有查询结果时候
            CLPlacemark *placemark = [placemarks objectAtIndex:0]; // 数组其实只有一个元素
            
            _lastCity = placemark.locality;
            //            [standard setObject:_lastCity forKey:CCLastCity];//省市地址
            _lastAddress = placemark.name;
            //            [standard setObject:_lastAddress forKey:CCLastAddress];//详细地址
            _pointLabel.text = [NSString stringWithFormat:@"%@ %@",_lastCity,_lastAddress];
            
        }
    }];
    

}


#pragma mark - 数据相关
- (void)requestWithlatitude:(float)latitude longtitude:(float)longtitude  start:(int)start count:(int)count{
    //1.拼接URL地址
    NSString *url = [NSString stringWithFormat:self.requestUrl,start,count,latitude,longtitude];
    NSLog(@"%@",url);
    NSLog(@"%f %f",latitude,longtitude);
    //百分号编码
    NSString *percentURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",percentURL);
    __weak typeof(self)weakSelf = self;
    
    [self.httpManager GET:percentURL parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        
        NSArray *array = responseObject[@"items"];
        NSArray *modelArray =[NSArray yy_modelArrayWithClass:[discoveryModel class] json:array];
        

        if (start == 0) {
            [weakSelf.collectionArray removeAllObjects];
        }
        [self.collectionArray addObjectsFromArray:modelArray];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView.mj_footer endRefreshing];
            weakSelf.collectionView.mj_footer.hidden = NO;
            weakSelf.collectionView.mj_header.hidden = NO;
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
    
}
@end
